package com.wythe.mall;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Intent;

import com.jiagu.sdk.BaseProtected;
import com.wythe.mall.activity.LoginActivity;
import com.wythe.mall.utils.SharePreferenceUtils;
import com.wythe.mall.utils.UserManager;

import java.util.List;

/**
 * 全局Applicaiton
 *
 * @author MapleStory
 * @ qq 1002285057
 * @ project https://gitee.com/MapStory/Shopwt-Android
 */

@SuppressWarnings("ALL")
public class BaseApplication extends Application {

    private static BaseApplication instance;

    public static BaseApplication get() {

        return instance;

    }

    //原生方法

    private native String getLocalAesKey();

    private native String getServerAesKey();

    //重写方法

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;
        BaseProtected.install(this);
        String token = SharePreferenceUtils.getString(this, "KEY_TOKEN");
        if (token != null && "".equals(token)) {
            UserManager.getInstance().setLogin(true);
        } else {
            UserManager.getInstance().setLogin(false);
        }
        //加载框架

    }

    //Activity销毁

    public void finish(Activity activity) {

        activity.finish();

    }

    public boolean inActivityStackTop() {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasksInfo = manager.getRunningTasks(1);
        if (tasksInfo.size() > 0) {
            if (getPackageName().equals(tasksInfo.get(0).topActivity.getPackageName())) {
                return true;
            }
        }
        return false;
    }

    public boolean inActivityStack(Class<?> cls) {
        Intent intent = new Intent(this, cls);
        ComponentName componentName = intent.resolveActivity(getPackageManager());
        boolean flag = false;
        if (componentName != null) {
            ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfoList = activityManager.getRunningTasks(10);
            for (ActivityManager.RunningTaskInfo taskInfo : taskInfoList) {
                if (taskInfo.baseActivity.equals(componentName)) {
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

    public boolean inActivityStackTop(Class<?> cls) {
        ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        String name = manager.getRunningTasks(1).get(0).topActivity.getClassName();
        return name.equals(cls.getName());
    }

    public void start(Activity activity, Class cls) {

        Intent intent = new Intent(activity, cls);
        activity.startActivity(intent);

    }

    //账号相关
}
